package com.pdd.controller;

import io.swagger.annotations.Api;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 文件上传控制器
 */
@Api(description = "文件上传接口",tags = {"文件上传接口"})
@CrossOrigin(origins = { "*" })
@Controller
public class UploadController {

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @ResponseBody
    public Map upload(MultipartFile file, HttpServletRequest request){
        String fileName = file.getOriginalFilename();
        long size = file.getSize();

        System.out.println("文件名："+fileName);
        System.out.println("大小："+size);

        //截取文件后缀名
        String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
        //随机生成新文件名:时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssms");
        String time = sdf.format(new Date());
        //随机生成新文件名:4位随机数
        Random random = new Random();
        int ranNum = random.nextInt(9000)+1000;
        //拼接，获取目标文件名
        String targetName = time+ranNum+suffix;
        //上传的目标文件夹
        String uploadDir = request.getServletContext().getRealPath("/upload");
        //如果目标文件夹不存在
        File dir = new File(uploadDir);
        if (!dir.exists()){
            dir.mkdir();
        }
        //将上传文件写入到目标位置
        File uploadFile = new File(uploadDir,targetName);
        try{
            file.transferTo(uploadFile);
        }catch (IOException e){
            e.printStackTrace();
        }
        Map<String,Object> map = new HashMap<>();
        map.put("file","/upload"+targetName);
        map.put("size",size);

        return map;
    }
}
